#pragma once
#include <unordered_map>
#include "log.hpp"

class Task
{
public:
    Task(int fd, char *ip, uint16_t& port, std::unordered_map<std::string,std::string> &dict)
    :sockfd_(fd),clientip_(ip),clientport_(port),dict_(dict)
    {
        
    }
    void run()
    {
        char buff[4096];
        int n = read(sockfd_,buff,sizeof(buff));
        if(n > 0)
        {
            buff[n] = '\0';
            std::string word(buff);
            std::string respon = "server echo#";
            printf("Client say# %s\n",buff);
            if(dict_.count(word))
            {
                respon += dict_[word];
            }
            else{
                respon += word;//echo
            }

            n = write(sockfd_,respon.c_str(),respon.size());

            if(n < 0)
            {
                 //服务启动已经忽略 SIGPIE 信号 , client关闭时,可能写崩溃
                Log("ERROR","write error: %s, sockfd: %d, clientip: %s, clientport: %d",strerror(errno),sockfd_,clientip_.c_str(),clientport_);
            }
            else if(n > 0)
            {
                Log("INFO","success service, sockfd: %d, clientip: %s, clientport: %d",sockfd_,clientip_.c_str(),clientport_);
            }
        }
        else if(n==0)
        {   //client断开读到0
            Log("INFO","client quit, sockfd: %d, clientip: %s, clientport: %d",sockfd_,clientip_.c_str(),clientport_);
        }
        else
        {
            Log("ERROR","read error, sockfd: %d, clientip: %s, clientport: %d",sockfd_,clientip_.c_str(),clientport_);
        }
        close(sockfd_);
    }
    ~Task(){}

private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
    std::unordered_map<std::string,std::string> &dict_;
};